package com.taptech.doufu.ui.fragment.NovelChildFragments;

//import android.app.Fragment;

import android.app.Fragment;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.constant.SPKey;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.ui.activity.NovelReadEndActivity;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.SharedPreferencesKey;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.db.history.Read_HirstoryUtil;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.ui.view.readview.BaseReadView;
import com.taptech.doufu.ui.view.readview.OnReadStateChangeListener;
import com.taptech.doufu.ui.view.readview.OverlappedWidget;
import com.taptech.doufu.ui.view.readview.util.CacheManager;
import com.taptech.doufu.services.GiftService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.ui.view.theme.read.ReadTheme;
import com.taptech.doufu.ui.view.theme.read.ReadThemeHelper;
import com.taptech.doufu.util.AesUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.MobileState;
import com.taptech.doufu.util.NoRepeatToast;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by op0509 on 2016/6/16.
 */
public class SectionDetailsLRFragmentNew extends Fragment implements HttpResponseListener, View.OnClickListener{

    private static final String TAG = "SectionDetailsLRFragmen";

    private static final String ARG_SECTION_id = "section_id";
    private static final String ARG_NOVEL_ID = "novel_id";
    private static final String ARG_ARTICLE_ITEM = "article_item";
    private static final String ARG_CAPTER_LIST = "capter_list";
    private static final String ARG_NOVEL_OFFLINE = "capter_list";


    private RelativeLayout rlTop;// 顶部布局

    private ProgressBar progressBar;// 加载提示
    private RelativeLayout rlPay;// 订阅布局
    private Button btnPay;// 订阅按钮
    private LinearLayout llAutoPay;// 自动订阅布局
    private ImageView imgAutoPay;// 自动订阅图标
    private View vsNotNetwork;// 无网布局
    private Button btnReload;// 重新下载
    private RelativeLayout payDialogLayout;
    private TextView payCancelBtn;
    private TextView jumpToPayBtn;
    private TextView payDesContentText;
    private TextView tvTip;

    private String sectionId;// 章节id
    private String novelId;// 小说id
    private String offLineNovelPath;// 离线小说路径
    private String articleTitle;// 章节title
    private String des;// 章节内容
    private String offlineData;//离线数据
    private JSONArray offlineArray;
    private int articleNum;// 章节总数
    private int articleItem;// 当前页码
    private boolean isOffLine = false;// 是否离线模式
    private boolean isYouthModel;

    public boolean isAutoPay() {
        return isAutoPay;
    }

    public void setAutoPay(boolean autoPay) {
        isAutoPay = autoPay;
    }

    private boolean isAutoPay = false;// 是否自动订阅
    public boolean isPay = true;// 是否已经付费过
    private boolean isLoginStateOld;// 记录获取数据时的登录状态
    private boolean isPaying = false;// 是否正在购买中


    public int currPage,currPos;//记录阅读的页数和每页字节的起始位置


    private HomeTopBean topicBean;
    private HomeTopBean contentBean;
    private TagsBean[] tagsBeans;

    private int indentType;//对齐方式
    private Read_HirstoryUtil mRead_HirstoryUtil;
    /** settings:字体设置 */
    private NovelSectionDetailsActivity activity;
    private ImageView mRedPacket;
    private Map<String, JSONObject> readPocketMap = new HashMap<>();

    private SparseArray<String> chaptersList;
    public void setChaptersList(SparseArray<String> array) {
        chaptersList = array;
        if (mPageWidget != null) {
            mPageWidget.setChaptersList(array);
        }
    }

    public static SectionDetailsLRFragmentNew newInstance(String sectionId, String novelId,SparseArray<String> chaptersList){
        SectionDetailsLRFragmentNew fragment = new SectionDetailsLRFragmentNew();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_SECTION_id, sectionId);
        bundle.putString(ARG_NOVEL_ID, novelId);
        bundle.putSerializable(ARG_CAPTER_LIST, (Serializable) chaptersList);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static SectionDetailsLRFragmentNew newInstance(String sectionId, String novelId){
        SectionDetailsLRFragmentNew fragment = new SectionDetailsLRFragmentNew();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_SECTION_id, sectionId);
        bundle.putString(ARG_NOVEL_ID, novelId);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static SectionDetailsLRFragmentNew newInstanceOffline(String sectionId, String offline,String novelId){
        SectionDetailsLRFragmentNew fragment = new SectionDetailsLRFragmentNew();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_SECTION_id, sectionId);
//        bundle.putString(ARG_NOVEL_OFFLINE, offline);
        bundle.putString(ARG_NOVEL_ID,novelId);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 设置标题
     * @param title
     */
    public void setCapterTitle(String title) {
        //设置标题
        if (!TextUtils.isEmpty(title)) {
            //绘制章节首页的大标题
            if (mPageWidget != null) {
                mPageWidget.setTitleText(title);
            }
        }
    }

    public void setCleanCache(boolean cleanCache) {
        isCleanCache = cleanCache;
    }

    private boolean isCleanCache = false;

    public void jumpToCapterNoLock(int chapter) {
        if (isCleanCache) {
            isCleanCache = false;
            removeCacheForAntoPay();
        }
        startRead = false;
        if (mPageWidget != null && chaptersList!=null&&chaptersList.size()>chapter-1) {
            sectionId = chaptersList.get(chapter-1);
            if (isOffLine) {
                showOffLine(chapter-1);
            } else {
                loadNovelDetailsList(sectionId);
            }
        }else{ //跳转到文评入口
            jumpToNovelToSweep();
        }
    }

    public void jumpToCapter(int chapter) {
        startRead = false;
        if (mPageWidget != null && chaptersList!=null&&chaptersList.size()>chapter-1) {
//            sectionId = chaptersList.get(chapter-1);
            if (!TextUtils.isEmpty(sectionId)) {
                if (CacheManager.getInstance().getChapterFile(novelId, chapter) == null){
                    if (isOffLine) {
                        showOffLine(chapter-1);
                    } else {
                        sectionId = chaptersList.get(chapter-1);
                        loadNovelDetailsList(sectionId);
                    }
                }else{
                    if (!startRead) {
                        startRead = true;
                        vsNotNetwork.setVisibility(View.GONE);
                        mPageWidget.jumpToChapter(chapter);
                    }
                }
            }
        }else{ //跳转到文评入口
            jumpToNovelToSweep();
        }
    }



    public SectionDetailsLRFragmentNew(){}

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.novel_details_list_item_lr, container, false);
        activity = (NovelSectionDetailsActivity) getActivity();
        indentType = DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_READ_INDENT,
                getActivity(), Constant.ReadIndentType.FORMAT);
        String pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, getActivity(), "");
        if (pwd != null && pwd.length() > 0) {
            isYouthModel = true;
        }
        initUI(view);
        initPayDialogView(view);
        initData();
//        initUIParams();
        initState();
        initPageWidge();
        setReadTheme(ReadThemeHelper.getReadTheme());
        if(activity != null && activity.mapContent.containsKey(sectionId)){
            contentBean = activity.mapContent.get(sectionId);
        }
        if(activity != null && activity.mapTopic.containsKey(sectionId)){
            topicBean = activity.mapTopic.get(sectionId);
            if (topicBean.getTags() != null && topicBean.getTags().length > 0)
            {
                tagsBeans = topicBean.getTags();
            }
            novelId = topicBean.getId();
            articleNum = Integer.valueOf(topicBean.getArticle_num());
            if (tagsBeans != null && tagsBeans.length > 0)
            {
                articleTitle = topicBean.getTitle();
            }
        }
        if (contentBean != null) {
            if(!isLoginStateOld && AccountService.getInstance().isLogin() && contentBean.isNeed_pay()){
                if(activity != null && activity.mapContent.containsKey(sectionId)){
                    activity.mapContent.remove(sectionId);
                }
                if(activity != null && activity.mapTopic.containsKey(sectionId)){
                    activity.mapTopic.remove(sectionId);
                }
            }else if(activity.isAutoPay && contentBean.isNeed_pay()){
                if(activity != null && activity.mapContent.containsKey(sectionId)){
                    activity.mapContent.remove(sectionId);
                }
                if(activity != null && activity.mapTopic.containsKey(sectionId)){
                    activity.mapTopic.remove(sectionId);
                }
            }
        }
        toGetNovelData();
        return view;
    }

    MobileState mobileState;
    private void initState() {
        mobileState = MobileState.getInstance();
        mobileState.initListenMobileState(new MobileState.StateChangeListener() {
            @Override
            public void onStateChanged() {
                if (mobileState != null && mPageWidget!=null){
                    mPageWidget.updateMobileState(mobileState);
                }
            }
        });
    }

    BaseReadView mPageWidget;
    FrameLayout flReadWidget;
    private void initPageWidge() {
        int fontSize = NovelSectionDetailsActivity.progressToFontSize(DiaoBaoSharedPreferences.getSharedPreferencesValueToInt(SharedPreferencesKey.SP_READ_PAGE_FONT_SIZE_STATE,
                getActivity(),1));
        float lineSpace = DiaoBaoSharedPreferences.getSharedPreferencesValueToFloat(SharedPreferencesKey.SP_READ_PAGE_READ_VERTICAL_SPACE,
                getActivity(), Constant.ReadSpace.NORMAL);
        mPageWidget = new OverlappedWidget(getActivity(), novelId,mobileState,fontSize,lineSpace,chaptersList, new ReadListener());
        flReadWidget.removeAllViews();
        flReadWidget.addView(mPageWidget);
        if (chaptersList != null) {
            mPageWidget.setChaptersList(chaptersList);
        }
    }

    public void jumpToNovelToSweep() {
        if (!TextUtils.isEmpty(novelId)) {
            NovelReadEndActivity.Companion.startActivity(getActivity(),Integer.parseInt(novelId));
        }
    }

    public void setStartRead(boolean startRead) {
        this.startRead = startRead;
    }

    public void setTempSectionId(String tempSectionId) {
        this.tempSectionId = tempSectionId;
    }

    private String tempSectionId = "";  //与startRead锁配合使用

    private boolean startRead = false;

    public synchronized void showChapterRead(String data, int chapter) { // 加载章节内容
        if (data != null) {
            CacheManager.getInstance().saveChapterFile(novelId, chapter, data,indentType);
        }
        if (!startRead ) {
            String id = activity.getmNovelDetailIds().get(chapter - 1);
            if (tempSectionId.equals("")||tempSectionId.equals(id)) {
                tempSectionId = "";
                startRead = true;
                sectionId = activity.getmNovelDetailIds().get(chapter-1);
                mPageWidget.removePageCache(chapter);

                if (activity.isFromCatalog() || chapter == activity.getmNovelDetailIds().size()) {
                    //如果从目录跳转 或者 最后一章不跳转到上次阅读页面
                    activity.setFromCatalog(false);
                    DiaoBaoSharedPreferences.setSharedPreferencesValueToString("read_horizontal_"+novelId,"",getActivity());
                    mPageWidget.jumpToChapter(chapter);
                }else{
                    String begin = DiaoBaoSharedPreferences.getSharedPreferencesValueToString("read_horizontal_" + novelId, getActivity(), "");
                    if (!TextUtils.isEmpty(begin)){
                        String[] strings = begin.split(" ");
                        DiaoBaoSharedPreferences.setSharedPreferencesValueToString("read_horizontal_"+novelId,"",getActivity());
                        if (strings.length > 1) {
                            mPageWidget.jumpToChapter(chapter,Integer.parseInt(strings[1]),Integer.parseInt(strings[0]));
                        }else{
                            mPageWidget.jumpToChapter(chapter);
                        }
                    }else{
                        mPageWidget.jumpToChapter(chapter);
                    }
                }
            }
        }
    }



    public void setFontSize(int size) {
        if (mPageWidget != null) {
            mPageWidget.setFontSize(size);
        }
    }

    public void setLineSpace(float space) {
        if (mPageWidget != null) {
            mPageWidget.setLineSpace(space);
        }
    }

    public void setAutoPlay(boolean isAutoPay) {
        if (mPageWidget != null) {
            mPageWidget.setAutoPlay(isAutoPay);
        }
    }

    public void updateSpeed(int allTime) {
        if (mPageWidget != null) {
            mPageWidget.updateSpeed(allTime);
        }
    }

    public void changePlayType(boolean isPlayLine) {
        if (mPageWidget != null) {
            mPageWidget.changePlayType(isPlayLine);
        }
    }

    public void setPlayType(boolean isPlayLine){
        if (mPageWidget != null) {
            mPageWidget.setPlayType(isPlayLine);
        }
    }

    public void waitPlay() {
        if (mPageWidget != null) {
            mPageWidget.waitPlay();
        }
    }

    public void restartPlay() {
        if (mPageWidget != null) {
            mPageWidget.restartPlay();
        }
    }

    public void setAutoPlayProgress(int changeHeight) {
        Log.d(TAG, "changeHeight==" + changeHeight);
        if (mPageWidget != null) {
            mPageWidget.setAutoPlayProgress(changeHeight);
        }
    }

    /**
     * 设置主题
     * @param readTheme
     */
    public void setReadTheme(ReadTheme readTheme) {
        if (mPageWidget != null) {
            mPageWidget.setReadTheme(readTheme);
        }
        try {
            if (ReadThemeHelper.bgIsPicture(readTheme)) {
                flReadWidget.setBackgroundResource(readTheme.getContentBg());
                rlPay.setBackgroundColor(activity.getResources().getColor(R.color.transparent_background));
            }else{
                flReadWidget.setBackgroundColor(activity.getResources().getColor(readTheme.getContentBg()));
                rlPay.setBackgroundColor(activity.getResources().getColor(readTheme.getContentBg()));
            }
            ReadBookUIUtil.setBtnUI(activity,btnPay,btnPayAll,llPayAllTip,tvPayAllTip,tvPayAllTipDesc);
            imgAutoPay.setImageResource(readTheme.getPayTheme().getIvAutoPayNone());
            tvAllPrice.setTextColor(activity.getResources().getColor(readTheme.getPayTheme().getDeleteLineFontColor()));
            ivHelp.setAlpha(readTheme.getPayTheme().getIvAlpha());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }

    }


    private synchronized void loadNovelDetailsList(String sectionId) {
        capterQuestCache.put(sectionId, sectionId);
        HomeMainServices.getInstance().loadNovelDetailsList(this, sectionId, 1);
    }



    /**
     * 同步正在阅读的章节数据
     */
    private synchronized void syncCurrCapter() {
        if (activity != null) {
            if (activity.mapTopic!=null &&
            activity.mapTopic.containsKey(sectionId)&&
                    activity.mapTopic.get(sectionId)!=null) {
                if (activity.mapContent !=null && activity.mapContent.get(sectionId)!=null &&
                        activity.mapContent.get(sectionId).isNeed_pay()){
                    if (activity.isShowTicketDialog()){
                        activity.showReadTicketDialog();
                    }
                }
                String tip = activity.mapTopic.get(sectionId).getTipinfo();
                if (!TextUtils.isEmpty(tip) && !tip.equals("null")) {
                    if (activity.mapTopic.get(sectionId).isVipFree()) {
                        String key = "show_tip_"+novelId;
                        boolean isCanShow = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(key, getActivity(), true);
                        if (isCanShow) {
                            DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(key, false, getActivity());
                            activity.mapTopic.get(sectionId).setTipinfo("");
                            UIUtil.showToast(WeMediaApplication.applicationContext,tip);
                        }
                    }else{
                        activity.mapTopic.get(sectionId).setTipinfo("");
                        UIUtil.showToast(WeMediaApplication.applicationContext,tip);
                    }

                }
            }
            boolean isHasSection = activity.mapContent.containsKey(sectionId);
            if (isHasSection) {
                //将数据存入缓存
                activity.setContentBean(activity.mapContent.get(sectionId));
                contentBean = activity.mapContent.get(sectionId);
                activity.setReadID(sectionId);
                int capter = getIndexOfVelue(chaptersList,sectionId)+1;
                if (!sectionId.equals(contentBean.getId())) {
                    return;
                }
                activity.setCurCapter(capter);
                //设置标题
                if (contentBean != null&& !TextUtils.isEmpty(contentBean.getTitle())) {
                    String title = contentBean.getTitle();
                    setCapterTitle(title);
                }
                if (contentBean != null) {
                    if (isOffLine) {
                        getOfflineLayout(contentBean.getArticle_status()== 0);
                    }else{
                        setIsPay(!contentBean.isNeed_pay());
                    }
                }
            }
            activity.setCommentCount();
        }
    }

    private Map<String,String> capterQuestCache = new HashMap<>();

    /**
     * 内存中是否存在该章节缓存
     * @param sectionId
     * @return
     */
    private boolean isHasCacheDataFromMap(String sectionId) {
        if (activity != null) {
            return activity.mapContent.containsKey(sectionId);
        }
        return false;
    }


    /**
     * 如果是自动订阅，则将以前付费的章节缓存清理掉
     */
    public void removeCacheForAntoPay() {
        capterQuestCache.clear();
        if (activity != null) {
            activity.mapContent.clear();
        }
        if (mPageWidget != null) {
            mPageWidget.clearPageAllCache();
        }
    }

    public void removeCacheForPay(String sectionId) {
        removeTempRequest(sectionId);
        if (activity != null) {
            activity.mapContent.remove(sectionId);
        }
        if (mPageWidget != null) {
            mPageWidget.clearPageAllCache();
        }
    }


    private int capterPageNum=0;

    private class ReadListener implements OnReadStateChangeListener {
        @Override
        public void onChapterChanged(int chapter) {
            if (chaptersList == null) {
                return;
            }
            boolean isIdChange = false;
            if (sectionId != chaptersList.get(chapter-1)){
                isIdChange = true;
                sectionId = chaptersList.get(chapter-1);
                if (activity != null) {
                    activity.addReadArticleNum();
                }
            }

            if (isIdChange){
                syncCurrCapter();
            }
            toReadInsert(sectionId);
//            if (topicBean != null && topicBean.isAutopay()) {
//
//            }else{
                //预加载
                if (contentBean!=null && contentBean.isNeed_pay() && !isAutoPay) {
                    //如果是需要付费的章节则加载多一些
                    for (int i = chapter - 3; i <= chapter + 3 && i <= chaptersList.size(); i++) {
                        if (i > 0 &&
                                (!isHasCacheDataFromMap(chaptersList.get(i-1))|| CacheManager.getInstance().getChapterFile(novelId, i) == null)) {
                            if (isOffLine) {
                                showOffLine(i-1);
                            } else {
                                if (!capterQuestCache.containsKey(chaptersList.get(i - 1))) {
                                    loadNovelDetailsList(chaptersList.get(i-1));
                                }
                            }
                        }
                    }
                } else {
                    // 加载前一节 与 后一节
                    for (int i = chapter - 1; i <= chapter + 1 && i <= chaptersList.size(); i++) {
                        if (i > 0 &&
                                (!isHasCacheDataFromMap(chaptersList.get(i-1))|| CacheManager.getInstance().getChapterFile(novelId, i) == null)) {
                            if (isOffLine) {
                                showOffLine(i-1);
                            } else {
                                if (!capterQuestCache.containsKey(chaptersList.get(i - 1))) {
                                    loadNovelDetailsList(chaptersList.get(i-1));
                                }
                            }
                        }
                    }
                }
//            }
        }

        @Override
        public void onPageChanged(int chapter, int page,int beginPos) {
            currPage = page;
            currPos = beginPos;
            if (page == capterPageNum) {
                if (page == 1) {
                    setReadPocketVisibility(View.GONE);
                } else {
                    try {
                        showReadPocket(chapter);
                    } catch (Exception e) {
                        setReadPocketVisibility(View.GONE);
                        e.printStackTrace();
                    }
                }
            }else{
                setReadPocketVisibility(View.GONE);
            }
        }

        @Override
        public void onLoadChapterFailure(int chapter) {
            startRead = false;
            if (chaptersList == null) {
                return;
            }
            if (!isHasCacheDataFromMap(chaptersList.get(chapter-1))|| CacheManager.getInstance().getChapterFile(novelId, chapter) == null){
                if (isOffLine) {
                    showOffLine(chapter-1);
                } else {
                    loadNovelDetailsList(chaptersList.get(chapter-1));
                }
            }
        }

        @Override
        public void onCenterClick() {
            //隐藏或显示导航栏
            setReadBar();
        }

        @Override
        public void onFlip() {
            //正在滑动，隐藏导航栏
            hideReadBar();
        }

        @Override
        public void onTheEnd() {
            if (activity != null && isAutoPay) {
                activity.exitAutoPlay();
                setAutoPlay(false);
            }
            if (vsNotNetwork.getVisibility() != View.VISIBLE) {
                jumpToNovelToSweep();
            }
        }

        @Override
        public void onPageNum(int pageNum) {
            capterPageNum = pageNum;
        }
    }

    private void setReadPocketVisibility(int state) {
        if (mRedPacket != null) {
            mRedPacket.setVisibility(state);
            if (mPageWidget != null) {
                if (state == View.VISIBLE) {
                    mPageWidget.setShowPocket(true);
                } else {
                    mPageWidget.setShowPocket(false);
                }
            }
        }
    }

    public void showReadPocket(int chapter) throws Exception{
        String sectionId = chaptersList.get(chapter-1);
        if (readPocketMap.containsKey(sectionId)) {
            JSONObject object = readPocketMap.get(sectionId);
            String redStatusPocket = object.getString("status");
            String reUserStatus = object.getString("user_status");
            if (redStatusPocket.equals("1") && (reUserStatus.equals("0") || reUserStatus.equals("2")  )) {//todo
                setReadPocketVisibility(View.VISIBLE);
            }else {
                setReadPocketVisibility(View.GONE);
            }
        } else {
            setReadPocketVisibility(View.GONE);
        }
    }

    private void hideReadBar() {
        if (activity != null) {
            activity.hideMenu();
        }
    }

    private void setReadBar() {
        if(activity != null) {
            if ((activity.isTopAndBottomVisiable || activity.isSecondMuneVisiable)&& !activity.isClickNOrPScroll) {
                activity.hideMenu();
            } else {
                activity.showFirstMenu();
            }
        }
    }



    private int dx;

    private TextView tvAllPrice;
    private LinearLayout llBuyAllTip;
    private FrameLayout btnPayAll;
    private TextView tvPayAllTip;
    private TextView tvPayAllTipDesc;
    private LinearLayout llPayAllTip;
    private ImageView ivLimitTime;
    private LinearLayout llHelp;
    private ImageView ivHelp;

    private void initUI(View view) {
        mRedPacket = (ImageView) view.findViewById(R.id.mRedPacket);
        mRedPacket.setOnClickListener(this);
        llHelp = (LinearLayout) view.findViewById(R.id.llHelp);
        ivHelp = (ImageView) view.findViewById(R.id.ivHelp);
        llHelp.setOnClickListener(this);
        flReadWidget = (FrameLayout) view.findViewById(R.id.flReadWidget);
        rlTop = (RelativeLayout) view.findViewById(R.id.rl_activity_novel_section_details_test_top);
        progressBar = (ProgressBar) view.findViewById(R.id.iv_dialog_waiting);
        rlPay = (RelativeLayout) view.findViewById(R.id.rl_novel_details_list_item_pay);
        tvTip = (TextView) view.findViewById(R.id.tvTip);
        btnPay = (Button) view.findViewById(R.id.btn_bottom_novel_section_details_pay);
        btnPay.setOnClickListener(this);
        tvPayAllTip = (TextView) view.findViewById(R.id.tvPayAllTip);
        tvPayAllTipDesc = (TextView) view.findViewById(R.id.tvPayAllTipDesc);
        llPayAllTip = (LinearLayout) view.findViewById(R.id.llPayAllTip);
        btnPayAll = (FrameLayout) view.findViewById(R.id.btnPayAll);
        ivLimitTime = (ImageView) view.findViewById(R.id.ivLimitTime);
        btnPayAll.setOnClickListener(this);
        llBuyAllTip = (LinearLayout) view.findViewById(R.id.llBuyAllTip);
        tvAllPrice = (TextView) view.findViewById(R.id.tvAllPrice);
        llAutoPay = (LinearLayout) view.findViewById(R.id.ll_bottom_novel_section_details_auto_pay);
        llAutoPay.setOnClickListener(this);
        imgAutoPay = (ImageView) view.findViewById(R.id.img_novel_details_list_item_auto_pay);
        vsNotNetwork = view.findViewById(R.id.vs_novel_details_list_item);
        btnReload = (Button) vsNotNetwork.findViewById(R.id.btn_common_novel_no_network);
        btnReload.setOnClickListener(this);
        vsNotNetwork.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setReadBar();
            }
        });
    }

    /**
     * 缺钱弹窗初始化
     */
    private void initPayDialogView(View view){
        payDialogLayout = (RelativeLayout) view.findViewById(R.id.pay_dialog_layout);
        payCancelBtn = (TextView) view.findViewById(R.id.pay_cancel_btn);
        jumpToPayBtn = (TextView) view.findViewById(R.id.jump_to_pay_btn);
        payDesContentText = (TextView) view.findViewById(R.id.text_des_content);
        payDialogLayout.setOnClickListener(this);
        payCancelBtn.setOnClickListener(this);
        jumpToPayBtn.setOnClickListener(this);
    }


    private void initData() {
        Bundle bundle = getArguments();
        sectionId = bundle.getString(ARG_SECTION_id);
        novelId = bundle.getString(ARG_NOVEL_ID);
        articleItem = bundle.getInt(ARG_ARTICLE_ITEM);
        if (activity != null) {
            offlineData = activity.getOffline();
        }
        //小说浏览历史数据
        mRead_HirstoryUtil = new Read_HirstoryUtil(getActivity());
    }

    private void toGetNovelData() {
        isLoginStateOld = AccountService.getInstance().isLogin();
        if (!TextUtil.isEmpty(offlineData)) {
            try {
                JSONObject data = new JSONObject(offlineData);
                //开启离线模式
                isOffLine = true;
                //文件中读取小说json信息
                JSONObject topicObject = data.getJSONObject("topic");
                offlineArray = data.getJSONArray("articles");
                if (topicBean == null)
                {
                    topicBean = new HomeTopBean();
                    topicBean.setJson2(topicObject);
                    if (activity != null) {
                        activity.topicBean = topicBean;
                    }
                    if (topicBean.getTags() != null && topicBean.getTags().length > 0)
                    {
                        tagsBeans = topicBean.getTags();
                    }
                    try
                    {
                        articleNum = Integer.valueOf(topicBean.getArticle_num());
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    if (tagsBeans!=null && tagsBeans.length > 0)
                    {
                        articleTitle = topicBean.getTitle();
                    }
                    activity.mapTopic.put(sectionId, topicBean);
                }
                int index = 0;
                for (int i=0;i<offlineArray.length();i++) {
                    JSONObject obj = offlineArray.getJSONObject(i);
                    if (obj.optString("id").equals(sectionId)) {
                        index = i;
                        break;
                    }
                }
                showOffLine(index);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            //如果有novelId
            if (!TextUtils.isEmpty(novelId))
            {// 推送跳转，没有novelId
                File novelDir = new File(Constant.AppDir.DIR_OFFLINE_DATA + "novel_" + novelId);
                // 如果离线存在
                if (novelDir != null && novelDir.exists())
                {
                    //开启离线模式
                    isOffLine = true;
                    offLineNovelPath = novelDir.getAbsolutePath();
                    File novelTopic = new File(offLineNovelPath + "/topic");
                    //文件中读取小说json信息
                    JSONObject topicObject = CacheUtil.readJsonDataFromCache(novelTopic);
                    if (topicBean == null)
                    {
                        topicBean = new HomeTopBean();
                        topicBean.setJson2(topicObject);
                        if (activity != null) {
                            activity.topicBean = topicBean;
                        }
                        if (topicBean.getTags() != null && topicBean.getTags().length > 0)
                        {
                            tagsBeans = topicBean.getTags();
                        }
                        try
                        {
                            articleNum = Integer.valueOf(topicBean.getArticle_num());
                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                        if (tagsBeans.length > 0)
                        {
                            articleTitle = topicBean.getTitle();
                        }
                        activity.mapTopic.put(sectionId, topicBean);
                    }
                    showOffLine(sectionId);
                } else {
                    toSendRequestData();
                }
            } else {
                toSendRequestData();
            }
        }
    }

    /**
     * 请求小说章节数据
     */
    public void toSendRequestData(){
        if(progressBar.getVisibility() != View.VISIBLE){
            progressBar.setVisibility(View.VISIBLE);
        }
        if(rlPay.getVisibility() == View.VISIBLE){
            rlPay.setVisibility(View.GONE);
        }
        capterQuestCache.put(sectionId, sectionId);
        HomeMainServices.getInstance().loadNovelDetailsList(this, sectionId, 1);
    }



    /**
     * 展示离线内容
     */
    private void showOffLine(int index) {
        try {
            JSONObject mainObject  = offlineArray.getJSONObject(index);
            contentBean = new HomeTopBean();
            contentBean.setJson(mainObject);
            if(!TextUtils.isEmpty(contentBean.getEncrypt_content())){// 兼容旧版本，旧版本离线的小说并没有该字段，还需使用旧字段
                des = AesUtil.desEncrypt(contentBean.getEncrypt_content(), AesUtil.getMD5(contentBean.getKey()).substring(0, 16));
            }else{
                des = contentBean.getDes();
            }
            activity.mapContent.put(contentBean.getId(), contentBean);
            if (sectionId.equals(contentBean.getId())) {
                syncCurrCapter();
            }
            StringBuilder data = new StringBuilder();
            if (contentBean.getArticle_status() == 0) {  //如果需要付费
                if (des.length() > 60) {
                    data.append(des.substring(0, 60)).append("...");
                } else {
                    data.append(des).append("...");
                }
            } else {
                data.append(des);
            }
            showChapterRead(data.toString(),index+1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 展示离线内容
     */
    private void showOffLine(String sectionId) {
        File novelFile = new File(offLineNovelPath + "/" + sectionId);
        JSONObject mainObject = CacheUtil.readJsonDataFromCache(novelFile);
        contentBean = new HomeTopBean();
        contentBean.setJson(mainObject);
        if(!TextUtils.isEmpty(contentBean.getEncrypt_content())){// 兼容旧版本，旧版本离线的小说并没有该字段，还需使用旧字段
            des = AesUtil.desEncrypt(contentBean.getEncrypt_content(), AesUtil.getMD5(contentBean.getKey()).substring(0, 16));
        }else{
            des = contentBean.getDes();
        }
        activity.mapContent.put(sectionId, contentBean);
        if (sectionId.equals(this.sectionId)) {
            syncCurrCapter();
        }
        int index = getIndexOfVelue(chaptersList,contentBean.getId());
        showChapterRead(contentBean.getContent(),index+1);
    }


    private void getOfflineLayout(boolean isShow) {
        if (isShow) {
            if(llAutoPay.getVisibility() == View.VISIBLE){
                llAutoPay.setVisibility(View.INVISIBLE);
            }
            rlPay.setVisibility(View.VISIBLE);
            btnPay.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor()));
            btnPay.setBackgroundResource(ReadThemeHelper.getReadTheme().getPayTheme().getBtnBg());
            imgAutoPay.setAlpha(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor());
            btnPay.setVisibility(View.VISIBLE);
            btnPayAll.setVisibility(View.INVISIBLE);
            llBuyAllTip.setVisibility(View.GONE);
            tvTip.setText("本章节未离线，请离线后阅读");
            btnPay.setText("马上下载");
        }else{
            rlPay.setVisibility(View.GONE);
        }
    }

    /**
     * 加载订阅布局
     * @param isPaid 是否支付过
     */
    public void setIsPay(boolean isPaid){
        isPay = isPaid;
        if(isPaid){
            if(rlPay.getVisibility() == View.VISIBLE){
                rlPay.setVisibility(View.GONE);
            }
        }else{
            setPayLayout();
        }
    }

    /**
     * 设置付费布局
     */
    public void setPayLayout(){
        if(rlPay.getVisibility() != View.VISIBLE){
            rlPay.setVisibility(View.VISIBLE);
        }
        ivLimitTime.setVisibility(View.GONE);
        if (AccountService.getInstance().isLogin()){// 已登录
            ReadBookUIUtil.setPayLayout(activity,topicBean,contentBean,btnPayAll,llBuyAllTip,tvTip,btnPay,ivLimitTime,llPayAllTip,tvPayAllTip,tvPayAllTipDesc,llAutoPay,tvAllPrice);
        } else {// 未登录
            if(llAutoPay.getVisibility() == View.VISIBLE){
                llAutoPay.setVisibility(View.INVISIBLE);
            }
            btnPay.setTextColor(getResources().getColor(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor()));
            btnPay.setBackgroundResource(ReadThemeHelper.getReadTheme().getPayTheme().getBtnBg());
            imgAutoPay.setAlpha(ReadThemeHelper.getReadTheme().getPayTheme().getBtnFontColor());
            btnPayAll.setVisibility(View.INVISIBLE);
            llBuyAllTip.setVisibility(View.GONE);
            btnPay.setText(activity.getResources().getString(R.string.login_go_logged));
        }
    }

    /**
     *  记录看过的小说章节id
     */
    public void toReadInsert(String readID){
        if (!TextUtils.isEmpty(readID))
        {
            mRead_HirstoryUtil.insertHirstory(novelId, readID);
        }
    }

    public void pageUp() {
        if (mPageWidget != null) {
            mPageWidget.pageUp();
        }
    }

    public void pageDown() {
        if (mPageWidget != null) {
            mPageWidget.pageDown();
        }
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        isPaying = false;
        if (handleType == HomeMainServices.HANDLE_TYPE_NOVEL_PAY_ALL_URL){
            //loading状态恢复
            if (response.getStatus() == 0 && response.getFail_code() == 0) {
                toSendRequestData();
                activity.toReloadPreviewAndNextData();
                removeCacheForAntoPay();
                startRead = false;
                Toast.makeText(getActivity(), "购买成功", Toast.LENGTH_LONG).show();
                return;
            }
            btnPay.setClickable(true);
            btnPayAll.setClickable(true);
        }
        if(progressBar.getVisibility() == View.VISIBLE){
            progressBar.setVisibility(View.GONE);
        }
        if(response.getStatus() == 0 && response.getFail_code() == 0){
            if (vsNotNetwork.getVisibility() == View.VISIBLE) {
                vsNotNetwork.setVisibility(View.GONE);
                setStartRead(false);
            }
            if (flReadWidget.getVisibility() != View.VISIBLE) {
                flReadWidget.setVisibility(View.VISIBLE);
            }
            try {
                JSONObject jsonObject = (JSONObject) response.getData();
                switch (handleType){
                    // 章节文字数据
                    case HomeMainServices.HANDLE_TYPE_LOAD_NOVEL_DETAILS:
                        activity.showHint();
                        toHandleData(jsonObject,false);
                        break;
                    case HomeMainServices.HANDLE_TYPE_BUY_CHARTER:// 购买章节
                        if(isAutoPay){
                            HomeMainServices.getInstance().getAutoPay(this, novelId);// 自动订阅
                            activity.toReloadPreviewAndNextData();
                        }
                        toHandleData(jsonObject,true);

                        break;
                    case HomeMainServices.HANDLE_TYPE_AUTO_PAY:// 自动订阅
//                        activity.toReloadSectionData();
                        break;
                    default:
                        break;
                }
            } catch (Exception e){
                capterQuestCache.clear();
                e.printStackTrace();
            }
        } else {
            capterQuestCache.clear();
            if(handleType == HomeMainServices.HANDLE_TYPE_BUY_CHARTER && response.getStatus() == 32){
                if (!payDialogLayout.isShown()){
                    TMAnalysis.event(activity , "3_7_Novelreading_purchase_section_Recharge");
                    payDialogLayout.setVisibility(View.VISIBLE);
                    payDesContentText.setText(response.getUser_msg());
                    return;
                }
            }
            NoRepeatToast.setToast(getActivity(), DiaobaoUtil.getErrorTips(response)).show();
            if(handleType == HomeMainServices.HANDLE_TYPE_LOAD_NOVEL_DETAILS && !isOffLine && vsNotNetwork.getVisibility() != View.VISIBLE){
                vsNotNetwork.setVisibility(View.VISIBLE);
                setReadBar();
//                flReadWidget.setVisibility(View.GONE);
                setStartRead(false);

            }
        }

    }



    private void toHandleData(JSONObject jsonObject,boolean isPay) throws Exception{
        // details
        JSONObject detail = jsonObject.getJSONObject("detail");
        HomeTopBean contentBean = new HomeTopBean();
        contentBean.setJson(detail);
        if(!TextUtils.isEmpty(contentBean.getEncrypt_content())){// 兼容旧版本，旧版本离线的小说并没有该字段，还需使用旧字段
            des = AesUtil.desEncrypt(contentBean.getEncrypt_content(), AesUtil.getMD5(contentBean.getKey()).substring(0, 16));
        }else{
            des = contentBean.getDes();
        }
        if (isPay && !contentBean.isNeed_pay()) {  //购买章节后获得数据
            try {
                activity.setSurplusTotal(Integer.parseInt(contentBean.getSpend_num()));
            } catch (Exception e) {
            }
        }
        // topic
        JSONObject topicObject = jsonObject.getJSONObject("topic");
        topicBean = new HomeTopBean();
        topicBean.setJson2(topicObject);


        if (jsonObject.has("tipinfo")){
            topicBean.setTipinfo(jsonObject.getString("tipinfo"));
        }
        if (!topicBean.isVipFree()){
            String key = "show_tip_"+novelId;
            boolean isCanShow = DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(key, getActivity(), false);
            if (!isCanShow) {
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(key,true,getActivity());
            }
        }


        activity.getPayInfo();
        if (activity != null) {
            activity.topicBean = topicBean;
        }
        if (topicBean.getTags() != null && topicBean.getTags().length > 0)
        {
            tagsBeans = topicBean.getTags();
        }
        novelId = topicBean.getId();
        articleNum = Integer.valueOf(topicBean.getArticle_num());
        if (activity != null) {
            activity.setArticleTitle(topicBean.getTitle());
            activity.setArticleNum(articleNum);
        }
        if (tagsBeans != null && tagsBeans.length > 0)
        {
            articleTitle = topicBean.getTitle();
        }
        activity.mapTopic.put(contentBean.getId(), topicBean);

        activity.mapContent.put(contentBean.getId(), contentBean);
        if (contentBean.getId().equals(sectionId)) {
            syncCurrCapter();
        }
        removeTempRequest(sectionId);
        int index = getIndexOfVelue(chaptersList,contentBean.getId());
        StringBuilder data = new StringBuilder();
        if (contentBean.isNeed_pay()) {  //如果需要付费
            if (des.length() > 60) {
                data.append(des.substring(0, 60)).append("...");
            } else {
                data.append(des).append("...");
            }
        } else {
            data.append(des);
        }
        showChapterRead(data.toString(),index+1);
        if (! detail.isNull("red_envelope")) {
            JSONObject red_pocket = detail.getJSONObject("red_envelope");
            readPocketMap.put(contentBean.getId(), red_pocket);
        }
    }

    private synchronized void removeTempRequest(String sectionId) {
        if (capterQuestCache.containsKey(sectionId)) {
            capterQuestCache.remove(sectionId);
        }
    }

    public static int getIndexOfVelue(SparseArray<String> array, String key) {
        if (array != null && !TextUtils.isEmpty(key)) {
            for (int i=0;i<array.size();i++) {
                if (key.equals(array.get(i))) {
                    return i;
                }
            }
        }
        return -1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("zyc","onDestroy");
        activity = null;
        if (mobileState != null) {
            mobileState.destoryListner();
        }
        CacheManager.getInstance().deletNovelFileById(novelId);
    }

    /** 返回章节title */
    public String getArticleTitle(){
        return articleTitle;
    }

    public HomeTopBean getTopicBean(){
        return topicBean;
    }

    public int getArticleItem(){
        return articleItem;
    }

    public int getRealIdsPos(){
        return articleItem-1;
    }

    public HomeTopBean getContentBean(){
        return contentBean;
    }

    /** 返回章节id */
    public String getSectionId(){
        return sectionId;
    }


    public void buyChapter() {
        if(!isPaying){
            isPaying = true;
            setStartRead(false);
            setTempSectionId(sectionId);
            removeCacheForAntoPay();
            TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section");
            int read_ticket_id = 0;
            if (activity.getPayInfoBean()!=null && activity.getPayInfoBean().getReadTicketInfo()!=null &&
                    activity.getPayInfoBean().getReadTicketInfo().getId() > 0) {
                read_ticket_id = activity.getPayInfoBean().getReadTicketInfo().getId();
            }
            HomeMainServices.getInstance().getBuyCharter(this, sectionId,read_ticket_id);// 购买章节
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnPayAll://完本购买
                if (isYouthModel) {
                    Toast.makeText(getActivity(),"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
//                tvPayAllTip.setText("购买中...");
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_BUY_FULL_NOVEL,novelId);
                btnPay.setClickable(false);
                btnPayAll.setClickable(false);
                if (tvPayAllTip.getText().toString().contains("完本")){
                    HomeMainServices.getInstance().loadPayAllNovel(this, novelId);
                }else{  //剩余章节购买
                    HomeMainServices.getInstance().loadPayVerbNovel(this, novelId);
                }
                break;
            case R.id.ll_novel_details_list_item:// 整体布局
                if(activity != null){
                    activity.isClickNOrPScroll = false;
                    if (activity.isTopAndBottomVisiable || activity.isSecondMuneVisiable) {
                        activity.hideMenu();
                    }else{
                        activity.showFirstMenu();
                    }
                }
                break;
            case R.id.btn_bottom_novel_section_details_pay:// 订阅按钮
                if (isYouthModel) {
                    Toast.makeText(getActivity(),"青少年模式不支持该功能",Toast.LENGTH_LONG).show();
                    return;
                }
                if (isOffLine) {
                    String url =  "TFNovel/TFOffLine.js?present=1&read=true&id=" +novelId;
                    DiaobaoBaseActivity activity = (DiaobaoBaseActivity) getActivity();
                    activity.presentWeexView(url);
                }else{
                    if(!AccountService.getInstance().isLogin()){// 判断是否已登录，如果未登录，则去登录
                        TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section_Signin");
                        AccountService.getInstance().jumpToLogin();
                        return;
                    }
                    buyChapter();
                }
                break;
            case R.id.ll_bottom_novel_section_details_auto_pay:// 自动订阅
                if(isAutoPay){
                    imgAutoPay.setImageResource(R.drawable.ugc_original_pic_default);
                }else{
                    imgAutoPay.setImageResource(R.drawable.ugc_original_pic_select);
                    TMAnalysis.event(getActivity(), "3_7_Novelreading_purchase_section_Continuouspurchase");
                }
                isAutoPay = !isAutoPay;
                activity.isAutoPay = isAutoPay;
                break;
            case R.id.btn_common_novel_no_network:// 重新加载
                if(progressBar.getVisibility() != View.VISIBLE){
                    progressBar.setVisibility(View.VISIBLE);
                }
                vsNotNetwork.setVisibility(View.GONE);
                HomeMainServices.getInstance().loadNovelDetailsList(this, sectionId, 1);
                break;
            case R.id.pay_cancel_btn:
                if (payDialogLayout.isShown()){
                    payDialogLayout.setVisibility(View.GONE);
                }
                break;
            case R.id.jump_to_pay_btn:
                TMAnalysis.event(activity , "jump_to_pay");
                GiftService.enterPayWebActivity(activity);
                break;
            case R.id.mRedPacket:
                try {
                    JSONObject redPocketStr = null;
                    if (readPocketMap.containsKey(sectionId)) {
                        redPocketStr = readPocketMap.get(sectionId);
                    }
                    if (topicBean != null && redPocketStr != null) {
                        redPocketStr.put("title",topicBean.getTitle());
                        redPocketStr.put("position","read");
                        String jsonStr = redPocketStr.toString();
                        String encodeJsonStr = URLEncoder.encode(jsonStr,"utf8");
                        String url =  "TFRedEnvelope/TFREStatus.js?present=1&needLogin=1&position=read" + "&data=" + encodeJsonStr;
                        DiaobaoBaseActivity activity = (DiaobaoBaseActivity) getActivity();
                        activity.presentWeexView(url);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            case R.id.llHelp:
                if (activity != null) {
                    activity.showBuyTipDialog();
                }
                break;
            default:
                break;
        }
    }

}
